package com.lebang.service.cences;

import com.lebang.domain.AppEarnNewsConfig;
import com.lebang.domain.CencesNewsJoke;
import com.lebang.example.CencesNewsJokeExample;
import com.lebang.mapper.AppEarnNewsConfigMapper;
import com.lebang.mapper.CencesNewsJokeMapper;
import com.lebang.mapper.LbbMemberMapper;
import com.lebang.mapper.MemberEarnLookRecordMapper;
import com.lebang.model.MyConfig;
import com.lebang.model.Whether;
import com.lebang.model.cences.CencesMsg;
import com.lebang.model.cences.NewsJokeRecordCount;
import com.lebang.service.BaseService;
import com.lebang.service.mongodb.CencesMsgMongodb;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 阅读赚  笑话 新闻
 *
 * @Author hwq
 * @Date 2020-02-06
 */
@Service
@Slf4j
public class CencesNewsJokeService extends BaseService<CencesNewsJoke, Integer, CencesNewsJokeExample> {
    @Autowired
    private CencesNewsJokeMapper baseMapper;
    @Autowired
    private LbbMemberMapper lbbMemberMapper;
    @Autowired
    private MemberEarnLookRecordMapper recordMapper;
    @Autowired
    private AppEarnNewsConfigMapper appEarnNewsConfigMapper;
    @Autowired
    private CencesMsgMongodb cencesMsgMongodb;

    public int deleteByTime(int time) {
        CencesNewsJokeExample earnDayExample = new CencesNewsJokeExample();
        earnDayExample.createCriteria().andTimeEqualTo(time).andAppIdEqualTo(MyConfig.getEnv());
        return baseMapper.deleteByExample(earnDayExample);
    }

    ;

    public void starDataInit(LocalDateTime end) {
        this.starDataInit(end, null);
    }

    public void starDataInit(LocalDateTime end, List<String> brand) {
        long starTime=System.currentTimeMillis();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd");
        LocalDateTime star = end.minusDays(1);
        int time = Integer.parseInt(end.toLocalDate().minusDays(1).format(df));

        if (brand == null) {
            brand = lbbMemberMapper.selectBrand();
        }

        //获取所有新闻赚和笑话赚
        List<NewsJokeRecordCount> newsJokeRecordCountList = recordMapper.countByDate(star, end);
        newsJokeRecordCountList.forEach(s->{s.setAppStoreIsNewMemberConfigId(s.getAppStore()+":"+s.getIsNewMember()+":"+s.getConfigId());});
        Map<String,List<NewsJokeRecordCount>> newsJokeRecords = newsJokeRecordCountList.stream().collect(Collectors.groupingBy(NewsJokeRecordCount::getAppStoreIsNewMemberConfigId));

        //总金币
        List<NewsJokeRecordCount> allMoneyList = recordMapper.countMoneyByDate(star, end);
        allMoneyList.forEach(s->{s.setAppStoreIsNewMemberConfigId(s.getAppStore()+":"+s.getIsNewMember()+":"+s.getConfigId());});
        Map<String,List<NewsJokeRecordCount>> allMoneyMap = allMoneyList.stream().collect(Collectors.groupingBy(NewsJokeRecordCount::getAppStoreIsNewMemberConfigId));

        //总金币翻倍
        List<NewsJokeRecordCount> doublePointList = recordMapper.countDoublePointByDate(star,end);
        doublePointList.forEach(s->{s.setAppStoreIsNewMemberConfigId(s.getAppStore()+":"+s.getIsNewMember()+":"+s.getConfigId());});
        Map<String,List<NewsJokeRecordCount>> doublePointMap = doublePointList.stream().collect(Collectors.groupingBy(NewsJokeRecordCount::getAppStoreIsNewMemberConfigId));

        AtomicInteger starInt = new AtomicInteger(0);
        AtomicInteger endInt = new AtomicInteger(0);
        List<AppEarnNewsConfig> list = appEarnNewsConfigMapper.selectByExample(null);
        for (AppEarnNewsConfig next : list) {
            List<CencesNewsJoke> cencesMasters = new ArrayList<>();
            //全部用户的
            brand.forEach(s -> {

                CencesNewsJoke newVo = new CencesNewsJoke(0, s, time, 1, 0, next.getId(), next.getTitle(),MyConfig.getEnv());
                CencesNewsJoke oldVo = new CencesNewsJoke(0, s, time, 0, 0, next.getId(), next.getTitle(),MyConfig.getEnv());
                CencesNewsJoke allVo = new CencesNewsJoke(0, s, time, 2, 0, next.getId(), next.getTitle(),MyConfig.getEnv());
                //1-10
                starInt.set(1);
                endInt.set(10);
                newVo.setTen(getNewsJokeCount(starInt.get(), endInt.get(),newsJokeRecords,s,next.getId(), Whether.YES.getDbIndex()));
                oldVo.setTen(getNewsJokeCount(starInt.get(), endInt.get(),newsJokeRecords,s,next.getId(), Whether.NO.getDbIndex()));
                allVo.setTen(newVo.getTen()+oldVo.getTen());
                //11-20
                starInt.set(11);
                endInt.set(20);
                newVo.setTwenty(getNewsJokeCount(starInt.get(), endInt.get(),newsJokeRecords,s,next.getId(), Whether.YES.getDbIndex()));
                oldVo.setTwenty(getNewsJokeCount(starInt.get(), endInt.get(),newsJokeRecords,s,next.getId(), Whether.NO.getDbIndex()));
                allVo.setTwenty(newVo.getTwenty()+oldVo.getTwenty());
                //21-30
                starInt.set(21);
                endInt.set(30);
                newVo.setThirty(getNewsJokeCount(starInt.get(), endInt.get(),newsJokeRecords,s,next.getId(), Whether.YES.getDbIndex()));
                oldVo.setThirty(getNewsJokeCount(starInt.get(), endInt.get(),newsJokeRecords,s,next.getId(), Whether.NO.getDbIndex()));
                allVo.setThirty(newVo.getThirty()+oldVo.getThirty());
                //30-100
                starInt.set(31);
                endInt.set(100);
                newVo.setForty(getNewsJokeCount(starInt.get(), endInt.get(),newsJokeRecords,s,next.getId(), Whether.YES.getDbIndex()));
                oldVo.setForty(getNewsJokeCount(starInt.get(), endInt.get(),newsJokeRecords,s,next.getId(), Whether.NO.getDbIndex()));
                allVo.setForty(newVo.getForty()+oldVo.getForty());
                //0-100
                starInt.set(1);
                endInt.set(100);
                newVo.setAllCount(getNewsJokeCount(starInt.get(), endInt.get(),newsJokeRecords,s,next.getId(), Whether.YES.getDbIndex()));
                oldVo.setAllCount(getNewsJokeCount(starInt.get(), endInt.get(),newsJokeRecords,s,next.getId(), Whether.NO.getDbIndex()));
                allVo.setAllCount(newVo.getAllCount()+oldVo.getAllCount());
                //总金币
                newVo.setAllMoney(getAllMoneyPoint(allMoneyMap,s,next.getId(), Whether.YES.getDbIndex()));
                oldVo.setAllMoney(getAllMoneyPoint(allMoneyMap,s,next.getId(), Whether.NO.getDbIndex()));
                allVo.setAllMoney(newVo.getAllMoney().add(oldVo.getAllMoney()));
                //总金币
                newVo.setLookVideoCount(getDoublePoint(doublePointMap,s,next.getId(), Whether.YES.getDbIndex()));
                oldVo.setLookVideoCount(getDoublePoint(doublePointMap,s,next.getId(), Whether.NO.getDbIndex()));
                allVo.setLookVideoCount(newVo.getLookVideoCount()+oldVo.getLookVideoCount());
                cencesMasters.add(newVo);
                cencesMasters.add(oldVo);
                baseMapper.insertAll(allVo);
                baseMapper.insertAll(newVo);
                baseMapper.insertAll(oldVo);
            });
            CencesNewsJoke item = new CencesNewsJoke(0, "all", time, 2, 1, next.getId(), next.getTitle(),MyConfig.getEnv());
            //新用户全部
            CencesNewsJoke newAll = new CencesNewsJoke(0, "all", time, 1, 1, next.getId(), next.getTitle(),MyConfig.getEnv());
            //老用户全部
            CencesNewsJoke oldAll = new CencesNewsJoke(0, "all", time, 0, 1, next.getId(), next.getTitle(),MyConfig.getEnv());

            cencesMasters.forEach(vo -> {
                sumBy(item, vo);
                if (vo.getCategory().equals(1)) {
                    sumBy(newAll, vo);
                }
                if (vo.getCategory().equals(0)) {
                    sumBy(oldAll, vo);
                }
            });
            baseMapper.insertAll(item);
            baseMapper.insertAll(newAll);
            baseMapper.insertAll(oldAll);
            //渠道的全部
            brand.forEach(s -> {
                CencesNewsJoke sjy = new CencesNewsJoke(0, s, time, 2, 1, next.getId(), next.getTitle(),MyConfig.getEnv());
                cencesMasters.forEach(vo -> {
                    if (vo.getBrand().equals(s)) {
                        sumBy(sjy, vo);
                    }
                });
                baseMapper.insertAll(sjy);
            });
        }
        cencesMsgMongodb.save(new CencesMsg("新闻笑话赚统计",(System.currentTimeMillis()-starTime)));
    }




    public CencesNewsJoke sumData(Integer star, Integer end, String appStore, int category, int type, Integer configId, String likeBrand) {
        return baseMapper.sumData(star, end, appStore, category, type, configId,likeBrand,MyConfig.getEnv());
    }
    private void sumBy(CencesNewsJoke item, CencesNewsJoke vo) {
        item.setTen(item.getTen() + vo.getTen());
        item.setTwenty(item.getTwenty() + vo.getTwenty());
        item.setThirty(item.getThirty() + vo.getThirty());
        item.setForty(item.getForty() + vo.getForty());
        item.setAllCount(item.getAllCount() + vo.getAllCount());
        item.setLookVideoCount(item.getLookVideoCount() + vo.getLookVideoCount());
        item.setAllMoney(item.getAllMoney().add(vo.getAllMoney()));
    }

    /**
     * 获取新闻笑话
     * @param star 开始
     * @param end 结束
     * @param newsJokeRecords 新闻笑话记录
     * @param appStore 渠道
     * @param configId 配置id
     * @param isNewMember 是否新老用户
     * @return 返回内容
     */
    private Integer getNewsJokeCount(int star, int end, Map<String, List<NewsJokeRecordCount>> newsJokeRecords, String appStore, Integer configId, Integer isNewMember) {
            Integer res=0;
            List<NewsJokeRecordCount> newsJokeRecordCountList = newsJokeRecords.get(appStore+":"+isNewMember+":"+configId);
            if(null==newsJokeRecordCountList){
                return res;
            }
            for(NewsJokeRecordCount newsJokeRecordCount:newsJokeRecordCountList){
                if(newsJokeRecordCount.getCount()>=star&&newsJokeRecordCount.getCount()<=end){
                    res=res+1;
                }
            }

            return res;
    }

    /**
     * 合计所有的金币
     * @param allMoneyMap 新闻笑话金币统计
     * @param appStore 渠道
     * @param configId 配置id
     * @param isNewMember 是否新老用户
     * @return 返回内容
     */
    private BigDecimal getAllMoneyPoint(Map<String, List<NewsJokeRecordCount>> allMoneyMap, String appStore, Integer configId, Integer isNewMember) {
        BigDecimal point = BigDecimal.ZERO;
        List<NewsJokeRecordCount> list = allMoneyMap.get(appStore+":"+isNewMember+":"+configId);
        if(null==list){
            return point;
        }
        for(NewsJokeRecordCount newsJokeRecordCount:list){
            point=point.add(newsJokeRecordCount.getPoint());
        }

        return point;
    }

    /***
     * 获取双倍金币统计数
     * @param doublePointMap 双倍金币数
     * @param appStore 渠道
     * @param configId 配置id
     * @param isNewMember 是否新老用户
     * @return 返回内容
     */
    private Integer getDoublePoint(Map<String, List<NewsJokeRecordCount>> doublePointMap, String appStore, Integer configId, Integer isNewMember) {
        AtomicInteger atomicInteger = new AtomicInteger(0);
        List<NewsJokeRecordCount> newsJokeRecordCountList = doublePointMap.get(appStore+":"+isNewMember+":"+configId);
        if(null==newsJokeRecordCountList){
            return atomicInteger.get();
        }
        newsJokeRecordCountList.forEach(s->{
            atomicInteger.addAndGet(atomicInteger.get()+s.getCount());
        });
        return atomicInteger.get();
    }

}
